package com.zhkj.txg.module.order.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.base.UploadResponse
import com.zhkj.lib.http.*
import com.zhkj.txg.module.find.entity.FindPictureEntity
import com.zhkj.txg.module.order.entity.DeliveryEntity
import com.zhkj.txg.module.order.entity.DeliveryResponse
import com.zhkj.txg.module.order.entity.RefundDetailResponse
import com.zhkj.txg.module.order.entity.RefundGoodsResponse
import com.zhkj.txg.module.order.model.OrderManager

class RefundViewModel(application: Application) : BaseViewModel(application) {
    private val orderManager = OrderManager()
    val refundGoodsLiveData = MutableLiveData<HttpResponse<RefundGoodsResponse>>()
    val refundSubmitLiveData = MutableLiveData<HttpResponse<BaseResponse>>()
    val refundDetailLiveData = MutableLiveData<HttpResponse<RefundDetailResponse>>()
    val refundUndoLiveData = MutableLiveData<HttpResponse<BaseResponse>>()
    val deliveryListLiveData = MutableLiveData<HttpResponse<DeliveryResponse>>()
    val submitDeliveryListLiveData = MutableLiveData<HttpResponse<BaseResponse>>()

    val entity: RefundUIEntity = RefundUIEntity()

    // 填写物流单号时才会初始化
    var deliveryEntity: DeliveryEntity? = null

    fun refundGoods(token: String, isGroup: Boolean = false) {
        val listener = ViewModelSubscribeListener(refundGoodsLiveData)
        val refundGoods =
            if (!isGroup) orderManager.refundGoods(token, entity.orderId, entity.goodsId, listener)
            else orderManager.groupRefundGoods(token, entity.orderId, entity.goodsId, listener)
        dispose.add(refundGoods)
    }

    fun refundSubmit(
        token: String,
        images: MutableList<FindPictureEntity>,
        isGroup: Boolean = false
    ) {
        uploadPicture(images, 0, token, isGroup)
    }

    fun refundDetail(token: String, isGroup: Boolean = false) {
        val listener = ViewModelSubscribeListener(refundDetailLiveData)
        val refundDetail =
            if (!isGroup) orderManager.refundDetail(token, entity.refundId, entity.orderId, entity.goodsId, listener)
            else orderManager.groupRefundDetail(token, entity.orderId, entity.goodsId, listener)
        dispose.add(refundDetail)
    }

    fun refundUndo(token: String, isGroup: Boolean = false) {
        val listener = ViewModelSubscribeListener(refundUndoLiveData)
        val refundUndo =
            if (!isGroup) orderManager.refundUndo(token, entity.orderId, entity.goodsId, listener)
            else orderManager.groupRefundUndo(token, entity.orderId, entity.goodsId, listener)
        dispose.add(refundUndo)
    }

    fun deliveryList() {
        val listener = ViewModelSubscribeListener(deliveryListLiveData)
        val deliveryList = orderManager.deliveryList(listener)
        dispose.add(deliveryList)
    }

    fun submitDelivery(token: String, shippingNo: String, isGroup: Boolean = false) {
        val listener = ViewModelSubscribeListener(submitDeliveryListLiveData)
        val submitDelivery =
            if (!isGroup) orderManager.submitDelivery(
                token,
                entity.orderId,
                entity.goodsId,
                deliveryEntity?.code ?: "",
                shippingNo,
                listener
            )
            else orderManager.groupSubmitDelivery(
                token,
                entity.orderId,
                entity.goodsId,
                deliveryEntity?.code ?: "",
                shippingNo,
                listener
            )
        dispose.add(submitDelivery)
    }

    /**
     * 递归图片数据上传图片
     */
    fun uploadPicture(images: MutableList<FindPictureEntity>, index: Int, token: String, isGroup: Boolean = false) {
        if (images.isNotEmpty() && index < images.lastIndex && !images[index].pictureFilePath.isNullOrBlank()) images[index].pictureFilePath?.let {
            val listener = object : SubscribeListener<UploadResponse> {
                override fun onStart() {
                    refundSubmitLiveData.postValue(HttpResponse<BaseResponse>().apply {
                        status = HttpResponseStatus.Status.START
                    })
                }

                override fun onSuccess(resp: UploadResponse) {
                    images[index].uploadUrl = resp.data?.url
                    uploadPicture(images, index + 1, token, isGroup)
                }

                override fun onFailure(throwable: Throwable) {
                    throwable.printStackTrace()
                    refundSubmitLiveData.postValue(HttpResponse<BaseResponse>().apply {
                        status = HttpResponseStatus.Status.FAILURE
                        val error = ResponseSubscribeListener.handleThrowable(throwable)
                        exception = error
                    })
                }
            }
            val uploadPicture = orderManager.uploadPicture(it, listener)
            dispose.add(uploadPicture)
        } else {
            val builder = StringBuilder()
            images.forEach { if (it.itemType == 1) builder.append(it.uploadUrl).append(",") }
            val imageStr =
                if (builder.isNotEmpty()) builder.deleteCharAt(builder.lastIndex).toString() else ""
            entity.images = imageStr
            submitRefund(token, isGroup)
        }
    }

    /**
     * 提交退款申请
     */
    private fun submitRefund(token: String, isGroup: Boolean = false) {
        val listener = ViewModelSubscribeListener(refundSubmitLiveData)
        val refundSubmit =
            if (!isGroup) orderManager.refundSubmit(
                token, entity.orderId, entity.goodsId, entity.type, entity.goodsStatus,
                entity.reason ?: "", entity.desc ?: "", entity.images ?: "", listener
            )
            else orderManager.groupRefundSubmit(
                token, entity.orderId, entity.goodsId, entity.type, entity.goodsStatus,
                entity.reason ?: "", entity.desc ?: "", entity.images ?: "", listener
            )
        dispose.add(refundSubmit)
    }
}

data class RefundUIEntity(
    var refundId: Long = 0,
    var orderId: Long = 0,
    var goodsId: Long = 0,
    var type: Int = 0,
    var goodsStatus: Int = 0,
    var reason: String? = null,
    var desc: String? = null,
    var images: String? = null
)